package com.fish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fish.dao.mapper.*;
import com.fish.model.entity.User;
import com.fish.model.vo.DashboardVO;
import com.fish.model.vo.UserStatisticsVO;
import com.fish.service.DashboardService;
import com.fish.common.util.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 仪表盘服务实现
 */
@Service
@RequiredArgsConstructor
public class DashboardServiceImpl implements DashboardService {

    private final UserMapper userMapper;
    private final OrganizationMapper organizationMapper;
    private final RoleMapper roleMapper;
    private final NotificationReceiverMapper notificationReceiverMapper;
    private final ChatMessageMapper chatMessageMapper;

    @Override
    public DashboardVO getDashboardData() {
        // 获取当前用户ID
        Long currentUserId = UserContext.getUserId();

        // 统计用户总数（@TableLogic自动过滤逻辑删除的）
        Long totalUsers = userMapper.selectCount(null);

        // 统计组织总数（@TableLogic自动过滤逻辑删除的）
        Long totalOrganizations = organizationMapper.selectCount(null);

        // 统计角色总数（@TableLogic自动过滤逻辑删除的）
        Long totalRoles = roleMapper.selectCount(null);

        // 统计今日新增用户数
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        Long todayNewUsers = userMapper.selectCount(
                new LambdaQueryWrapper<User>()
                        .between(User::getCreateTime, todayStart, todayEnd)
        );

        // 统计未读通知数
        Long unreadNotifications = notificationReceiverMapper.selectCount(
                new LambdaQueryWrapper<com.fish.model.entity.NotificationReceiver>()
                        .eq(com.fish.model.entity.NotificationReceiver::getReceiverId, currentUserId)
                        .eq(com.fish.model.entity.NotificationReceiver::getIsRead, false)
        );

        // 统计待处理消息数（未读消息）
        Long pendingMessages = chatMessageMapper.selectCount(
                new LambdaQueryWrapper<com.fish.model.entity.ChatMessage>()
                        .eq(com.fish.model.entity.ChatMessage::getReceiverId, currentUserId)
                        .eq(com.fish.model.entity.ChatMessage::getIsRead, false)
        );

        // 计算系统运行天数（从最早的用户创建时间开始计算）
        Long systemRunningDays = 0L;
        User earliestUser = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .orderByAsc(User::getCreateTime)
                        .last("LIMIT 1")
        );
        if (earliestUser != null && earliestUser.getCreateTime() != null) {
            LocalDate systemStartDate = earliestUser.getCreateTime().toLocalDate();
            systemRunningDays = ChronoUnit.DAYS.between(systemStartDate, LocalDate.now());
        }

        // 统计在线用户数（查询最近5分钟内有活动的用户）
        LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
        Long onlineUsers = userMapper.selectCount(
                new LambdaQueryWrapper<User>()
                        .eq(User::getStatus, 1)
                        .ge(User::getUpdateTime, fiveMinutesAgo)
        );

        return DashboardVO.builder()
                .totalUsers(totalUsers)
                .totalOrganizations(totalOrganizations)
                .totalRoles(totalRoles)
                .todayNewUsers(todayNewUsers)
                .unreadNotifications(unreadNotifications)
                .pendingMessages(pendingMessages)
                .systemRunningDays(systemRunningDays)
                .onlineUsers(onlineUsers)
                .build();
    }

    @Override
    public List<UserStatisticsVO> getUserStatistics() {
        List<UserStatisticsVO> statisticsList = new ArrayList<>();

        // 获取最近7天的用户注册统计（@TableLogic自动过滤逻辑删除的）
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            LocalDateTime dayStart = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime dayEnd = LocalDateTime.of(date, LocalTime.MAX);

            Long count = userMapper.selectCount(
                    new LambdaQueryWrapper<User>()
                            .between(User::getCreateTime, dayStart, dayEnd)
            );

            statisticsList.add(UserStatisticsVO.builder()
                    .date(date.toString())
                    .count(count)
                    .build());
        }

        return statisticsList;
    }
}

